#!/bin/bash

# This is a dotfiles manager written by notabug.org/anxpydev
# It is written in pure bash using only GNU coreutils like find, grep, sed and awk

# The rdm variable syntax is the following

# Inside vars file:
# # Comment
# let varName = value
# let varName1 = !command that outputs value
# let varName2 = !command ^varName
# In the last example ^varName will get substituted like in any file

# Inside any dot file to substitute variable name
# ^varName^

makeVars() {
    # Creates a temporary variable file where all 'metavariables' are substituted
    varFile="$(cat vars)"
    lIdx=1
    lTot=$(echo "$varFile" | wc -l)
    while [[ 1 ]]; do
	line="$(echo "$varFile" | sed -n "$lIdx"p"")"
	if [[ $(echo "$line" | cut -b 1-3) = "let" ]]; then
	    p2="$(echo "$line" | awk '{split($0, a, " = "); print a[2]}')"
	    val=
	    if [[ "$(echo "$p2" | cut -b 1)" = "!" ]]; then
		val="$(eval "$(echo "$p2" | cut -b 2-)")"
		varFile="${varFile//"$p2"/"$val"}"
	    else
		val="$p2"
	    fi

	    varFile="${varFile//"^$(echo $line | awk '{print $2}')^"/"$val"}"
	fi
	if [[ $lIdx = $lTot ]]; then
	    break
	fi
	lIdx=$(expr $lIdx + 1)
	
    done
    echo "$varFile" > vars.tmp
}

replace() {
    while IFS= read -r line; do
	if [[ $(echo "$line" | cut -b 1) = "#" ]]; then
	    continue
	fi
	varName="$(echo "$line" | awk '{print $2}')"
  varValue="$(echo "$line" | awk '{split($0, a, " = "); print a[2]}')"
	files="$(grep -rl "\^$varName\^" "$1")"
	if ! [[ $files ]]; then
	    continue
	fi
	while IFS= read -r file; do
	    echo "$varName -> $file"
	    contents="$(cat $file)"
	    echo "${contents//"^$varName^"/"$varValue"}" > $file
	done <<< "$files"
    done < vars.tmp
}

makeFiles() {
    if [[ -d $1_tmp ]]; then
	rm -rf $1_tmp
	mkdir $1_tmp
    fi
    mkdir $1_tmp
    
    cp -rfv files/$1/* $1_tmp
    replace "$1_tmp"
}

SUDO=
if ! [[ -e vars ]]; then touch vars; fi
if ! [[ -d files ]]; then mkdir files; fi
if ! [[ -d files/root ]]; then mkdir files/root; fi
if ! [[ -d files/home ]]; then mkdir files/home; fi

shopt -s dotglob

if echo "$@" | grep -q "\-su"; then
    SUDO=sudo
fi
    

if echo "$@" | grep -q "\-mv"; then
    makeVars
    cp -fv vars.tmp finVars
fi

if echo "$@" | grep -q "\-mf"; then
    makeVars
    makeFiles home
fi

if echo "$@" | grep -q "\-r"; then
    makeVars
    replace "$2"
fi

if echo "$@" | grep -q "\-i"; then
    makeVars
    makeFiles home
    cp -rfv home_tmp/* /home/$(whoami)
    if [[ $SUDO ]]; then
	makeFiles root
	sudo cp -rfv root_tmp/* /
    fi
    if [[ -e postInstall.sh ]]; then
	bash postInstall.sh
    fi	
    if [[ -e preInstall.sh ]]; then
	bash preInstall.sh
    fi	
fi


if [[ -e vars.tmp ]]; then rm -f vars.tmp; fi
if [[ -e home_tmp ]]; then rm -rf home_tmp; fi
if [[ -e root_tmp ]]; then rm -rf root_tmp; fi
